package com.studentapp.tool;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.Map;
import java.util.concurrent.ExecutionException;

public class VolleyTool {
    private static final String TAG = "VolleyTool";


    /**
     * 需在线程中调用
     * @param context 上下文
     * @param url 请求地址
     * @param body 待传输的JSON数据
     * @return 服务器返回的JSON数据
     */
    public static String getPostResponse(Context context, String url,JSONObject body) {
        RequestQueue queue = Volley.newRequestQueue(context);
        RequestFuture<JSONObject> future = RequestFuture.newFuture();
        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.POST,
                url,
                body,
                future,
                future
        );
        queue.add(request);
        JSONObject response = null;
        try {
            response = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return response.toString();
    }

    /**
     * 需在线程中调用
     * @param context 上下文
     * @param url 请求地址
     * @return 服务器返回的JSON数据
     */
    public static String getPostResponse(Context context, String url) {
        RequestQueue queue = Volley.newRequestQueue(context);
        RequestFuture future = RequestFuture.newFuture();
        StringRequest request = new StringRequest(
                Request.Method.POST,
                url,
                future,
                future
        );
        queue.add(request);
        String response = null;
        try {
            response = (String) future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return response;
    }
}
